﻿#region

using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;
using InvoiceChecking.Settings.BusinessLayer;
using InvoiceChecking.Web.UI;
using WebCommon;

#endregion

public partial class JournalEditPage : Page
{
    public bool IsEditable = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtilBase.RedirectAfterInsertUpdate(FormView1, "JournalVoucherEdit.aspx?{0}", JournalVoucherDataSource);
        FormUtilBase.RedirectAfterAddNew(FormView1, "JournalVoucherEdit.aspx");
        FormUtilBase.RedirectAfterCancel(FormView1, "JournalVoucher.aspx");
        FormUtilBase.SetDefaultMode(FormView1, "JournalVoucherId");
        if (!IsPostBack)
        {
            var dataSet = DataRepository.SunAccountCodeProvider.GetList();
            dataAccountCode.DataSource = dataSet.Tables[0];
            dataAccountCode.DataBind();
            var tcodes = DataRepository.Provider.ExecuteDataSet("_TCode_GetList");
            dataT0.DataSource = tcodes.Tables[0].Select("Tcode='T0'").CopyToDataTable();
            dataT0.DataBind();
            dataT1.DataSource = tcodes.Tables[0].Select("Tcode='T1'").CopyToDataTable();
            dataT1.DataBind();
            dataT2.DataSource = tcodes.Tables[0].Select("Tcode='T2'").CopyToDataTable();
            dataT2.DataBind();
            dataT3.DataSource = tcodes.Tables[0].Select("Tcode='T3'").CopyToDataTable();
            dataT3.DataBind();
            if (Request.QueryString["Message"] != null)
            {
                string script = string.Format("openDialog('{0}');", Request.QueryString["Message"]);
                Page.ClientScript.RegisterStartupScript(GetType(), "welcome", script, true);
            }
        }
    }

    protected void FormView1_Load(object sender, EventArgs e)
    {
        var dataPreparedBy = (DropDownList)FormView1.Row.FindControl("dataPreparedBy");
        dataPreparedBy.Enabled = false;
        var txtJournalId = (TextBox)FormView1.Row.FindControl("dataJournalVoucherId");
        txtJournalId.Enabled = false;
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            var txtJournalVoucherDate = (TextBox)FormView1.Row.FindControl("dataJournalVoucherDate");
            var dataExchangeRate = (TextBox)FormView1.Row.FindControl("dataExchangeRate");
            if (string.IsNullOrEmpty(dataExchangeRate.Text))
                dataExchangeRate.Text = SharedFunction.GetVCBHCMExchangeRate();
            if (string.IsNullOrEmpty(txtJournalVoucherDate.Text))
                txtJournalVoucherDate.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            var voidButton = (HtmlControl)FormView1.Row.FindControl("VoidButton");
            voidButton.Style.Add("display", "none");
            dataPreparedBy.SelectedValue = Context.User.Identity.Name.Split('\\')[1];
            //IsEditable = true;
        }
        else
        {
            //var dataJournalVoucherTypeId = (EntityDropDownList)FormView1.Row.FindControl("dataJournalVoucherTypeId");
            //dataJournalVoucherTypeId.Enabled = false;
            FormView1.FooterRow.FindControl("PreviewButton").Visible = true;
            var journalVoucherId = Request.QueryString["JournalVoucherId"];
            var objJournalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
            if (objJournalVoucher.IsVoid)
            {
                var voidButton = (HtmlControl)FormView1.Row.FindControl("VoidButton");
                voidButton.Style.Add("display", "none");
            }
            if (objJournalVoucher.IsVoid || objJournalVoucher.IsApproved || objJournalVoucher.IsCompleted ||
                objJournalVoucher.ExportedDate.HasValue)
                IsEditable = false;
            else
                IsEditable = true;
        }
        // To bind visible value
        pn_JournalVoucherDetailsAdd.Visible = IsEditable;
    }

    protected void JournalVoucherDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {

        var journalVoucherDate = Convert.ToDateTime(e.InputParameters["JournalVoucherDate"].ToString());
        int count;
        var jvCode = ServiceFacade.SettingsHelper.JournalVoucherPrefix;
        var journalVouchers =
            DataRepository.JournalVoucherProvider.GetPaged(
                "JournalVoucherId LIKE '" + jvCode + journalVoucherDate.ToString("yyMM") + "%'",
                "JournalVoucherId DESC", 0, 1, out count);
        string journalVoucherId;
        if (count > 0)
        {
            journalVoucherId = jvCode + journalVoucherDate.ToString("yyMM") +
                               string.Format("{0:000}", int.Parse(journalVouchers[0].JournalVoucherId.Substring(7)) + 1);
        }
        else
        {
            journalVoucherId = jvCode + journalVoucherDate.ToString("yyMM") + "001";
        }
        e.InputParameters["JournalVoucherId"] = journalVoucherId;
        var attachFile = (FileUpload)FormView1.FindControl("dataAttachFile");
        if (attachFile.HasFile)
        {
            var fileName = journalVoucherId + Path.GetExtension(attachFile.PostedFile.FileName);
            attachFile.SaveAs(Server.MapPath("~/AttachFile/Journal/") + fileName);
            e.InputParameters["AttachFile"] = fileName;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        string whereExpression = string.Format("Accnt_Code='{0}'", dataAccountCode.SelectedValue);
        int count;
        VList<SunAccountCode> accountCodes = DataRepository.SunAccountCodeProvider.GetPaged(whereExpression, "", 0, 1,
                                                                                            out count);
        bool error = false;
        var content = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
        div_DetailsError.InnerHtml = "";
        if (string.IsNullOrEmpty(dataAmount.Value))
        {
            div_DetailsError.InnerHtml +=
                @"<div class='notification error png_bg'> <div>Please input Amount</div></div>";
            error = true;
        }
        else
        {
            decimal result;
            if (!decimal.TryParse(dataAmount.Value, out result))
            {
                div_DetailsError.InnerHtml +=
                    @"<div class='notification error png_bg'> <div>Please input valid Amount</div></div>";
                error = true;
            }
        }
        if (string.IsNullOrEmpty(dataAccountCode.SelectedValue))
        {
            div_DetailsError.InnerHtml +=
                @"<div class='notification error png_bg'> <div>Please input Account Code</div></div>";
            error = true;
        }
        else
        {
            for (int i = 0; i < 4; i++)
            {
                if (accountCodes[0].EnterAnal[i] == 'Y')
                {
                    var comboBox = (EntityDropDownList)content.FindControl("dataT" + i.ToString(CultureInfo.InvariantCulture));
                    if (string.IsNullOrEmpty(comboBox.SelectedValue))
                    {
                        div_DetailsError.InnerHtml += @"<div class='notification error png_bg'> <div>Please input T" +
                                                      i.ToString(CultureInfo.InvariantCulture) + "</div></div>";
                        error = true;
                    }
                }
            }
            for (int i = 4; i < 9; i++)
            {
                if (accountCodes[0].EnterAnal[i] == 'Y')
                {
                    var input =
                        (HtmlInputControl)content.FindControl("dataT" + i.ToString(CultureInfo.InvariantCulture));
                    if (string.IsNullOrEmpty(input.Value))
                    {
                        div_DetailsError.InnerHtml +=
                            @"<div class='notification error png_bg'> <div>Please input T" + i.ToString(CultureInfo.InvariantCulture) + "</div></div>";
                        error = true;
                    }
                }
            }
        }
        if (!error)
        {
            if (btnSave.Text == "Add Detail")
            {
                var journalVoucherDetail = new JournalDetails
                    {
                        Amount = decimal.Parse(dataAmount.Value),
                        AccountCode = dataAccountCode.SelectedValue.Trim(),
                        MoneyType = dataMoneyType.SelectedValue,
                        JournalVoucherId = Request.QueryString["JournalVoucherId"],
                        DebitCredit = dataDebitCredit.SelectedValue,
                        Description = dataDescription.Text,
                        T0 = dataT0.SelectedValue,
                        T1 = dataT1.SelectedValue,
                        T2 = dataT2.SelectedValue,
                        T3 = dataT3.SelectedValue,
                        T4 = dataT4.Value,
                        T5 = dataT5.Value,
                        T6 = dataT6.Value,
                        T7 = dataT7.Value,
                        T8 = dataT8.Value
                    };
                DataRepository.JournalDetailsProvider.Insert(journalVoucherDetail);
            }
            else if (btnSave.Text == "Update Detail")
            {
                var journalVoucherDetail = (JournalDetails)Session["JournalVoucherDetail"];
                journalVoucherDetail.Amount = Decimal.Parse(dataAmount.Value);
                journalVoucherDetail.AccountCode = dataAccountCode.SelectedValue;
                journalVoucherDetail.MoneyType = dataMoneyType.SelectedValue;
                journalVoucherDetail.DebitCredit = dataDebitCredit.SelectedValue;
                journalVoucherDetail.Description = dataDescription.Text;
                journalVoucherDetail.T0 = dataT0.SelectedValue;
                journalVoucherDetail.T1 = dataT1.SelectedValue;
                journalVoucherDetail.T2 = dataT2.SelectedValue;
                journalVoucherDetail.T3 = dataT3.SelectedValue;
                journalVoucherDetail.T4 = dataT4.Value;
                journalVoucherDetail.T5 = dataT5.Value;
                journalVoucherDetail.T6 = dataT6.Value;
                journalVoucherDetail.T7 = dataT7.Value;
                journalVoucherDetail.T8 = dataT8.Value;
                DataRepository.JournalDetailsProvider.Update(journalVoucherDetail);
                Session["JournalVoucherDetail"] = null;
            }
            ClearInputForm();
        }
    }

    private void ClearInputForm()
    {
        btnSave.Text = "Add Detail";
        dataAmount.Value = "";
        dataAccountCode.SelectedValue = null;
        dataMoneyType.SelectedValue = "VND";
        dataDebitCredit.SelectedValue = "Debit";
        dataDescription.Text = "";
        dataT0.SelectedValue = null;
        dataT1.SelectedValue = null;
        dataT2.SelectedValue = null;
        dataT3.SelectedValue = null;
        dataT4.Value = "";
        dataT5.Value = "";
        dataT6.Value = "";
        dataT7.Value = "";
        dataT8.Value = "";
        GridViewJournalVoucherDetail1.DataBind();
        btnCancel.Visible = false;
        //dataAccountCode.Focus();
    }

    protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "Print")
        {
            var journalVoucherId = Request.QueryString["JournalVoucherId"];
            Response.Redirect("ReportJournalVoucher.aspx?JournalVoucherId=" + journalVoucherId, true);
        }
    }

    protected void btnVoid_Click(object sender, EventArgs e)
    {
        var journalVoucherId = Request.QueryString["JournalVoucherId"];
        VoidJournalVoucher(journalVoucherId, dataVoidReason.Text);
    }

    private void VoidJournalVoucher(string journalVoucherId, string voidReason)
    {
        var journalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
        journalVoucher.IsVoid = true;
        journalVoucher.VoidBy = Context.User.Identity.Name.Split('\\')[1];
        journalVoucher.VoidDate = DateTime.Now;
        journalVoucher.VoidReason = voidReason;
        journalVoucher.IsCompleted = true;
        DataRepository.JournalVoucherProvider.Update(journalVoucher);
    }

    protected void GridViewJournalVoucherDetail1_DataBound(object sender, EventArgs e)
    {
        //Calculate Amount in footer row
        if (GridViewJournalVoucherDetail1.Rows.Count > 0)
        {
            Decimal totalAmount = 0;
            foreach (GridViewRow dataRow in GridViewJournalVoucherDetail1.Rows)
            {
                if (dataRow.Cells[5].Text == "Debit")
                    totalAmount -= decimal.Parse(dataRow.Cells[4].Text);
                else
                    totalAmount += decimal.Parse(dataRow.Cells[4].Text);
            }
            GridViewJournalVoucherDetail1.FooterRow.Cells[4].Text = String.Format("{0:#,0.00}", totalAmount);
        }
    }

    protected void GridViewJournalVoucherDetail1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DetailEdit")
        {
            btnSave.Text = "Update Detail";
            btnCancel.Visible = true;
            var journalVoucherDetailId = Int32.Parse(e.CommandArgument.ToString());
            var journalVoucherDetail = DataRepository.JournalDetailsProvider.GetByJournalDetailId(journalVoucherDetailId);
            dataAmount.Value = journalVoucherDetail.Amount.ToString();
            dataAccountCode.SelectedValue = journalVoucherDetail.AccountCode;
            dataMoneyType.SelectedValue = journalVoucherDetail.MoneyType;
            dataDebitCredit.SelectedValue = journalVoucherDetail.DebitCredit;
            dataDescription.Text = journalVoucherDetail.Description;
            dataT0.SelectedValue = journalVoucherDetail.T0;
            dataT1.SelectedValue = journalVoucherDetail.T1;
            dataT2.SelectedValue = journalVoucherDetail.T2;
            dataT3.SelectedValue = journalVoucherDetail.T3;
            dataT4.Value = journalVoucherDetail.T4;
            dataT5.Value = journalVoucherDetail.T5;
            Session["JournalVoucherDetail"] = journalVoucherDetail;
        }
        else if (e.CommandName == "Clone")
        {
            btnCancel.Visible = true;
            var journalVoucherDetailId = Int32.Parse(e.CommandArgument.ToString());
            var journalVoucherDetail = DataRepository.JournalDetailsProvider.GetByJournalDetailId(journalVoucherDetailId);
            dataAmount.Value = journalVoucherDetail.Amount.ToString();
            dataAccountCode.SelectedValue = journalVoucherDetail.AccountCode;
            dataMoneyType.SelectedValue = journalVoucherDetail.MoneyType;
            dataDebitCredit.SelectedValue = journalVoucherDetail.DebitCredit;
            dataDescription.Text = journalVoucherDetail.Description;
            dataT0.SelectedValue = journalVoucherDetail.T0;
            dataT1.SelectedValue = journalVoucherDetail.T1;
            dataT2.SelectedValue = journalVoucherDetail.T2;
            dataT3.SelectedValue = journalVoucherDetail.T3;
            dataT4.Value = journalVoucherDetail.T4;
            dataT5.Value = journalVoucherDetail.T5;
            dataT6.Value = journalVoucherDetail.T6;
            dataT7.Value = journalVoucherDetail.T7;
            dataT8.Value = journalVoucherDetail.T8;
            dataAccountCode.Focus();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearInputForm();
    }
    protected void JournalVoucherDataSource_Updating(object sender, ObjectDataSourceMethodEventArgs e)
    {
        var journalVoucherId = e.InputParameters["JournalVoucherId"];
        var attachFile = (FileUpload)FormView1.FindControl("dataAttachFile");
        if (attachFile.HasFile)
        {
            var fileName = journalVoucherId + Path.GetExtension(attachFile.PostedFile.FileName);
            attachFile.SaveAs(Server.MapPath("~/AttachFile/Journal/") + fileName);
            e.InputParameters["AttachFile"] = fileName;
        }
    }

    protected void btnClone_Click(object sender, EventArgs e)
    {
        string journalVoucherId = Request.QueryString["JournalVoucherId"];
        var cloneJournal = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
        var journalDate = DateTime.Parse(txt_VoucherDateClone.Text);
        DataRepository.JournalVoucherProvider.DeepLoad(cloneJournal);
        int count;
        var jvCode = ServiceFacade.SettingsHelper.JournalVoucherPrefix;
        var journalVouchers =
            DataRepository.JournalVoucherProvider.GetPaged(
                "JournalVoucherId LIKE '" + jvCode + journalDate.ToString("yyMM") + "%'",
                "JournalVoucherId DESC", 0, 1, out count);
        if (count > 0)
        {
            journalVoucherId = jvCode + journalDate.ToString("yyMM") +
                               string.Format("{0:000}", int.Parse(journalVouchers[0].JournalVoucherId.Substring(7)) + 1);
        }
        else
        {
            journalVoucherId = jvCode + journalDate.ToString("yyMM") + "001";
        }
        cloneJournal.JournalVoucherDate = journalDate;
        cloneJournal.JournalVoucherId = journalVoucherId;
        cloneJournal.IsNew = true;
        cloneJournal.PreparedBy = Context.User.Identity.Name.Split('\\')[1];
        cloneJournal.IsSentForApproval = false;
        cloneJournal.IsCompleted = false;
        cloneJournal.ExportedDate = null;
        cloneJournal.ExportedBy = null;
        cloneJournal.IsVoid = false;
        cloneJournal.VoidBy = null;
        cloneJournal.VoidDate = null;
        cloneJournal.IsApproved = false;
        cloneJournal.ApprovedDate = null;
        cloneJournal.Reason = "";
        DataRepository.JournalVoucherProvider.Insert(cloneJournal);
        foreach (var detail in cloneJournal.JournalDetailsCollection)
        {
            detail.JournalVoucherId = journalVoucherId;
            detail.IsNew = true;
            DataRepository.JournalDetailsProvider.Insert(detail);
        }
        Response.Redirect("JournalVoucherEdit.aspx?JournalVoucherId=" + journalVoucherId + "&Message=CloneSuccess", true);
    }
}